import React, {useEffect, useState} from 'react';
import {useLocation, useNavigate} from "react-router-dom";

import './index.css';
import {Input, message, Pagination, Spin} from "antd";
import http from "../../../util/http";
import defaultImg from './image/default.png'
import header from "../../../components/Header";
import { Divider, List, Typography } from 'antd';
import {EnvEnums, EnvType, useAppContext} from "../../../App";
const {Search} = Input;
// import parse from 'html-react-parser';
// 全站搜索
function GlobalSearch(props) {
    let navigate = useNavigate();
    const location = useLocation();
    const state = location.state || {}
    const params = state.params || {}
    const { keywords } = params;
    const dirId = params.dirId || -1;
    const [data, setData] = useState([]);
    const [total, setTotal] = useState(0)
    const [loading, setLoading] = useState(false);
    const [search,setSearch] = useState("")
    const { env,setEnv } = useAppContext();

    const [page, setPage] = useState({
        total: 0,
        pageNum: 1,
        pageSize: 10
    });
    useEffect(() => {
        setLoading(true)
        // const params = {
        //     key: keywords,
        //     loginid: 1,
        //     contentType: "DOC",
        //     page: page.pageNum,
        //     pagepernum: page.pageSize,
        //     sysVersion: 9,
        // }
        if (env === EnvEnums.prod){
            const queryString = `/baseapp/ws/get?language=${encodeURIComponent(7)}&key=${encodeURIComponent(keywords)}&page=${page.pageNum}&pagepernum=${page.pageSize}`;

            http.doGet(queryString).then(res => {
                const  {result,FLAG,recordCount} = res;
                if (FLAG === "0") {
                    const list = result
                        .filter(item => { return item && item.schema === 'DOC'})
                        .map(item => {

                            const {head,schema,other,contents,footer} = item
                            if (schema === "DOC"){
                                const otherObj = JSON.parse(other);
                                return {
                                    docContent: head.title,
                                    docCreateDate: otherObj.date,
                                    docSubject: otherObj.title,
                                    id: head.id,
                                }
                            }
                        })
                    setTotal(recordCount)
                    setData(list)
                }
                setLoading(false)
            }).catch(reason => {
                message.error(reason.message)
                setLoading(false)
            })
        }else {
            const params = new URLSearchParams();
            params.append('key', keywords);
            params.append('page', page.pageNum);
            params.append('pagepernum', page.pageSize);

            params.append('loginid', 1);
            params.append('contentType', 'DOC');
            params.append('sysVersion', 9);

            http.doPost('/api/fullsearch/base/doSearch',
                params, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }
            ).then(res => {
                const  {result,FLAG,recordCount} = res;
                if (FLAG === "0") {
                    const list = result
                        .filter(item => { return item && item.schema === 'DOC'})
                        .map(item => {

                            const {head,schema,other,contents,footer} = item
                            if (schema === "DOC"){
                                const otherObj = JSON.parse(other);
                                return {
                                    docContent: head.title,
                                    docCreateDate: otherObj.date,
                                    docSubject: otherObj.title,
                                    id: head.id,
                                }
                            }
                        })
                    setTotal(recordCount)
                    setData(list)
                }
                setLoading(false)
            }).catch(reason => {
                message.error(reason.message)
                setLoading(false)
            })
        }


        // http.doPost('/doc/getdoc', {category: dirId, pageSize: page.pageSize, pageNum: page.pageNum,search: search}).then(res => {
        //     if (res.status === 200) {
        //         setData(res.data.list)
        //         setTotal(res.data.totalCount)
        //     }
        //     setLoading(false)
        // }).catch(reason => {
        //     message.error(reason.message)
        //     setLoading(false)
        // })

    }, [page, keywords,search])

    function openUrl(docId) {
        if (docId && docId !== "") {
            navigate('/portal/details?hiddenLeft=1', {
                state: {docId, page: state.page, text: state.text,params:params}
            });
        }
    }

    const onChange = (current, pageSize) => {
        setPage({
            pageNum: current,
            pageSize: pageSize
        })
    };

    const onSearch = (value) => {
        if (!loading) {
            setSearch(value)
        }
    }

    return (
        <div className="portal-search-main">
            {/*<Search*/}
            {/*    placeholder="请输入查询内容"*/}
            {/*    allowClear*/}
            {/*    enterButton="查询"*/}
            {/*    size="large"*/}
            {/*    onSearch={onSearch}*/}
            {/*    disabled={loading}*/}
            {/*    style={{ width: 304,float:'right',marginBottom:20}}*/}
            {/*/>*/}
            <div style={{clear: "both"}}/>
            <Spin spinning={loading}>
                {/*<div className="portal-search-table">*/}
                {/*    {*/}
                {/*        data && data.map((item, index) => {*/}
                {/*            // let imgUrl;*/}
                {/*            // if (item.imgUrl && item.imgUrl !== "") {*/}
                {/*            //     imgUrl = item.imgUrl*/}
                {/*            // }else {*/}
                {/*            //     imgUrl = defaultImg*/}
                {/*            // }*/}
                {/*            return (*/}
                {/*                <div className="portal-search-item" key={index} onClick={() => openUrl(item.id)}>*/}
                {/*                    /!*<div className="portal-project-item-img">*!/*/}
                {/*                    /!*    <img src={imgUrl} style={{width: "100%", height: "100%"}} alt=""/>*!/*/}
                {/*                    /!*</div>*!/*/}
                {/*                    <div className="portal-search-item-text" title={item.docSubject}>*/}
                {/*                        <span>{item.docSubject}</span>*/}
                {/*                    </div>*/}
                {/*                </div>*/}
                {/*            )*/}
                {/*        })*/}
                {/*    }*/}
                {/*</div>*/}
                <List
                    bordered
                    dataSource={data}
                    renderItem={(item) => (
                        <List.Item
                            onClick={() => openUrl(item.id)}
                        >
                            <div dangerouslySetInnerHTML={{__html: item.docSubject}}></div>
                        </List.Item>
                    )}
                />
                <div className="portal-search-pagination">
                    <Pagination
                        showSizeChanger
                        showQuickJumper
                        showTotal={(total) => `共${total}条`}
                        current={page.pageNum}
                        pageSize={page.pageSize}
                        total={total}
                        hideOnSinglePage={false}
                        onChange={onChange}
                    />
                </div>
            </Spin>
        </div>
    );
}

export default GlobalSearch;